<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\LocationService;
use app\admin\service\ServiceService;
use app\admin\service\UsersService;
use app\admin\validate\Service as ServiceValidate;
use app\AdminController;
use think\exception\ValidateException;
use think\facade\Log;
use wxpay\Wxsend;

class Service extends AdminController
{
    /**
     * 上门服务列表
     * @return \think\response\Json|\think\response\View
     */
    public function index()
    {
        if (request()->isPost()) {
            $keywords = trim($this->request->param('keywords', ''));
            $where = [];
            if ($keywords) {
                $where[] = ['u.nickname|s.name|s.mobile|s.company', 'like', '%' . $keywords . '%'];
            }

            $list = ServiceService::getServiceList($where, $this->page, $this->pagesize);
            $count = ServiceService::countServiceList($where);
            return adminResponseJson(['count' => $count, 'list' => $list]);
        }

        // 服务数据总数
        $countService = ServiceService::countService();
        // 0等待中
        $waitService = ServiceService::countService(['status' => 0]);
        // 1服务中
        $visitService = ServiceService::countService(['status' => 1]);
        // 2已完成
        $endService = ServiceService::countService(['status' => 2]);
        // 服务地区分布
        $serviceArea = ServiceService::getServiceArea();
        return view('', [
            'service_data' => [
                'countService' => $countService,
                // 待服务
                'waitService' => $waitService,
                'waitLastService' => $countService - $waitService,
                'waitServiceScale' => $waitService && $countService ? round(($waitService / $countService) * 100, 2) . '%' : '0%',
                // 服务中
                'visitService' => $visitService,
                'visitLastService' => $countService - $visitService,
                'visitServiceScale' => $visitService && $countService ? round(($visitService / $countService) * 100, 2) . '%' : '0%',
                // 已完成
                'endService' => $endService,
                'endLastService' => $countService - $endService,
                'endServiceScale' => $endService && $countService ? round(($endService / $countService) * 100, 2) . '%' : '0%',
                'serviceArea' => $serviceArea
            ]
        ]);
    }

    /**
     * 服务编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function serviceEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $info = ServiceService::findService(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $info['home_time'] = date('Y-m-d H:i:s', $info['home_time']);

        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(ServiceValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $isExists = ServiceService::findService([
                ['id', '<>', $data['id']],
                ['resource_number', '=', $data['resource_number']],
            ]);
            if ($isExists) {
                $this->error(adminJsonMsg(1008));
            }

            if (strtotime($data['home_time']) < time()) {
                $this->error(adminJsonMsg(1009));
            }

            $data['home_time'] = strtotime(date('Y-m-d H:i', strtotime($data['home_time'])));

            ServiceService::updateService($data, ['id' => $data['id']]);

            $this->success('操作成功', (STRING)url('/service/index'));
        }

        // 省份
        $province = LocationService::getProvince();
        // 城市
        $city = LocationService::getCity($info['province']);
        // 地区
        $area = LocationService::getArea($info['city']);

        return view('', ['info' => $info, 'province' => $province, 'city' => $city, 'area' => $area]);
    }

    /**
     * 服务详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function serviceShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $info = ServiceService::findService(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $info['home_time'] = date('Y-m-d H:i:s', $info['home_time']);
        $info['province'] = LocationService::getLocationValue(['location_id' => $info['province']]);
        $info['city'] = LocationService::getLocationValue(['location_id' => $info['city']]);
        $info['area'] = LocationService::getLocationValue(['location_id' => $info['area']]);

        return view('', ['info' => $info]);
    }

    /**
     * 状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        $id = intval($this->request->param('id', 0));
        $field = $this->request->param('field', 'status');
        // 标识：0删除 其他=>状态(1服务中   2已完成)
        $tips = intval($this->request->param('tips', 0));
        $where = ['id' => $id];
        $find = ServiceService::findService($where);
        if (!$find) {
            $this->error(adminJsonMsg(1002));
        }
        if (!$tips) {
            $update = [$field => -1];
        } else {
            if (!$find[$field]) {
                // 推送模板消息
                $pub_openid = UsersService::findUsersValue(['id' => $find['uid']]);
                if ($pub_openid) {
                    Log::write('用户' . $find['uid'] . '公众号openid存在，推送模板消息', 'error');
                    $send = new Wxsend();
                    $keyword1 = '测试人员';
                    $keyword2 = '13666666666';
                    $keyword3 = '上门服务';
                    $keyword4 = date('Y-m-d H:i');
                    $send->sendMsg($pub_openid, 17, $keyword1, $keyword2, $keyword3, $keyword4);

                } else {
                    Log::write('用户' . $find['uid'] . '公众号openid不存在', 'error');
                }
                $update = [$field => 1, 'service_time' => time()];
            } else {
                $update = [$field => 2, 'end_time' => time()];
            }
        }
        $res = ServiceService::updateService($update, $where);
        if (!$res) {
            $this->error(adminJsonMsg(1003));
        }
        $this->success('success');
    }
}